import java.util.Stack;

public class CommonAncestor {

    Stack<TreeNode> stackP = new Stack<>();
    Stack<TreeNode> stackQ = new Stack<>();

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    private boolean pushByTravel(TreeNode root ,Stack<TreeNode> stack,TreeNode key){
        if(root == null || key == null){
            return false;
        }
        stack.push(root);
        if(root == key){
            return true;
        }

        //将root左子树上的节点压栈
        boolean flag1 = pushByTravel(root.left, stack, key);
        if(flag1){
            return true;
        }


        //右子树压栈
        boolean flag2 = pushByTravel(root.right, stack, key);
        if(flag2){
            return true;
        }

        //root.left  root.right 都没有key时 将压入的节点弹出 也就是根节点到key路径上并不会包含这个节点
        stack.pop();
        return false;
    }


    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null){
            return null;
        }
        pushByTravel(root,stackP,p);
        pushByTravel(root,stackQ,q);
        int lengthQ = stackQ.size();
        int lengthP = stackP.size();
        int length = lengthP - lengthQ;
        if(length >= 0){
            int tmp = length;
            while(tmp > 0){
                stackP.pop();
                tmp--;
            }
        }
        if(length < 0){
            int tmp = length;
            while(tmp < 0){
                stackQ.pop();
                tmp++;
            }
        }

        while(stackQ.peek() != stackP.peek()){
            stackQ.pop();
            stackP.pop();
        }
        return stackQ.peek();
    }

}
